import 'package:bilibili/basic/http/core/hi_error.dart';
import 'package:bilibili/basic/http/dao/login_dao.dart';
import 'package:bilibili/basic/util/toast.dart';
import 'package:bilibili/basic/widget/appbar.dart';
import 'package:bilibili/basic/widget/login_button.dart';
import 'package:bilibili/basic/widget/login_effect.dart';
import 'package:bilibili/basic/widget/login_input.dart';
import 'package:flutter/material.dart';

class LoginPage extends StatefulWidget {
  final VoidCallback? onJumpRegistion;
  final VoidCallback? onSuccess;
  const LoginPage({Key? key, this.onJumpRegistion, this.onSuccess}) : super(key: key);
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {

  bool protect = false;
  bool _loginEnable = false;
  String userName = "";
  String password = "";
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: appBar("密码登录", '注册', () {
        if (widget.onJumpRegistion != null) {
          widget.onJumpRegistion!();
        }
      }),
      body: Container(
        child: ListView(
          children: [
            LoginEffect(protect: protect),
            LoginInput(title: '用户名', hint: '请输入用户名', onChanged: (value) {
              userName = value;
              checkInput();
            }),
            LoginInput(title: '密码', hint: '请输入密码', onChanged: (value) {
              password = value;
              checkInput();
            }),
            LoginButton('登录', enable: _loginEnable, onPressed: () {
              _send();
            })
          ],
        ),
      ),
    );
  }

  void checkInput() {
    if (userName.isNotEmpty && password.isNotEmpty) {
      _loginEnable = true;
    } else {
      _loginEnable = false;
    }
    setState(() {});
  }

  void _send() async {
    try {
      var result = await LoginDao.login(userName, password);
      if (result['code'] == 0) {
        showToast("登录成功");
        if (widget.onSuccess != null) {
          widget.onSuccess!();
        }
      } else {
        showWarnToast(result['msg']);
      }
    } on HiNetError catch(e) {
      print(e);
    }
  }
}
